package com.example.tool.action.listener;

import com.example.tool.action.ActionUtil;
import com.example.tool.ui.HToolIcon;
import com.example.tool.utils.FileUtil;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@SuppressWarnings("Duplicates")
public class OrganizationEventListenerActions extends AnAction {

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return super.getActionUpdateThread();
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    ActionUtil.ActionCreatInput(e, (information, value) -> {
      String[] configInformation = ActionUtil.getInformation(e.getProject());
      if (configInformation != null) {
        String className = value.get(0);
        // xx.java
        FileUtil.generateFile(information[0] + "/" + className + ".java", "/demo/init/listener/OrganizationEventListener.txt",
            str -> str.replace("$package$", information[1])
                .replace("$ClassName$", className)
                .replace("$TIME$", new SimpleDateFormat("yyyy-MM-dd").format(new Date())));

        // spring-xx-listener.xml
        String xmlPath = Objects.requireNonNull(e.getProject()).getBasePath() + "/" + configInformation[2] + "/WEB-INF/cfgHome/plugin/" + configInformation[1] + "/spring";
        String filePath = xmlPath + "/spring-" + configInformation[1] + "-listener.xml";
        FileUtil.generateFile(filePath, "/demo/spring/spring-demo.txt",
            str -> ActionUtil.appendNewBean(str, filePath, information, className));
        VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
      } else {
        Messages.showMessageDialog(
            e.getProject(),
            "The seeyon configuration file is required, but the corresponding file is not found or the file is incorrect, please reset it!",
            "Error",
            HToolIcon.ModuleIcon);
      }
    }, "组织监听类名: ");
  }

  @Override
  public void update(@NotNull AnActionEvent event) {
    ActionUtil.ActionP(event);
  }
}
